import axios from "axios";
import NProgress from 'nprogress';
import feedback from "@/utils/feedback";
import cache from "@/utils/cache";
import {CacheEnum} from "@/enums/cacheEnum";
import {ContentTypeEnum, RequestCodeEnum} from "@/enums/requestEnum";
import router from '@/router'
import {PageEnum} from "@/enums/pageEnum";
import {clearAll} from "@/utils/auth";

// NProgress配置
NProgress.configure({showSpinner: false})

const service = axios.create({
    baseURL: import.meta.env.BASE_URL,
    timeout: 5000,
    headers: {"Content-Type": ContentTypeEnum.JSON}
});

service.interceptors.request.use((config) => {
    NProgress.start();

    const token = cache.get(CacheEnum.TOKEN_KEY);
    if (token) {
        config.headers.token = token;
    }
    return config;
}, (err) => {
    return err
});

service.interceptors.response.use((response) => {
    NProgress.done()

    // console.log(response.config)
    // console.log(response.data)
    const {code, data, msg} = response.data
    if (RequestCodeEnum.SUCCESS === code) {
        return data;
    } else if (RequestCodeEnum.TOKEN_ERROR === code ||
        RequestCodeEnum.TOKEN_NOT_FOUND === code ||
        RequestCodeEnum.TOKEN_EXPIRE === code) {
        clearAll()
        router.push(PageEnum.LOGIN)
        return Promise.reject()
    } else {
        feedback.msgError(msg)
        return Promise.reject(data)
    }

}, (err) => {
    return Promise.reject(err)
});

export default service;